package com.star.httpclient;

import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

import java.io.IOException;
import java.net.CookieHandler;
import java.net.CookieManager;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.Locale;
import java.util.ResourceBundle;

public class GetCookieTest {

    private final HttpClient httpClient;
    private String url;

    public GetCookieTest() {
        // 创建 CookieManager 并设置为默认的 CookieHandler
        // 自动管理cookies
        CookieManager cookieManager = new CookieManager();
        CookieHandler.setDefault(cookieManager);
        this.httpClient = HttpClient.newBuilder()
                .cookieHandler(cookieManager)
                .build();
    }

    @BeforeTest
    public void readProperties() {
        ResourceBundle bundle = ResourceBundle.getBundle("app", Locale.CHINA);
        url = bundle.getString("testUrl");
    }

    @Test
    public void test1() throws IOException, InterruptedException {
        // 创建一个HTTP请求 指定URI
        HttpRequest httpRequest = HttpRequest.newBuilder()
                .uri(URI.create(url + "/getCookies")) // 使用 URI 创建请求
                .build();

        // 发送 HTTP 请求并获取响应
        HttpResponse<String> response = httpClient.send(
                httpRequest, HttpResponse.BodyHandlers.ofString());

        // 输出响应的状态码和响应体
        System.out.println("响应状态码：" + response.statusCode());
        System.out.println("响应体：" + response.body());
    }

    @Test(dependsOnMethods = {"test1"})
    public void test2() throws IOException, InterruptedException {
        // 创建一个HTTP请求 指定URI
        HttpRequest httpRequest = HttpRequest.newBuilder()
                .uri(URI.create(url + "/getWithCookies")) // 使用 URI 创建请求
                .build();

        // 发送 HTTP 请求并获取响应
        HttpResponse<String> response = httpClient.send(
                httpRequest, HttpResponse.BodyHandlers.ofString());

        assert response.statusCode() == 200;
    }
}
